import Request from '@/utils/luch-request/luch-request/index.js';
import store from '@/store/index.js'; // 引入 Vuex store
const http = new Request();
const apiUrl = 'https://juanjiahui.guguan.net/web/'
const loginRequest = (options = {}) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: apiUrl + options.url || '',
			method: options.type || 'GET',
			data: options.data || {},
		}).then(data => {
			let [err, res] = data;
			resolve(res);
		}).catch(error => {
			reject(error)
		})
	});
}
const request = (options = {}) => {
	// 在这里可以对请求头进行一些设置
	const token = store.state.token;
	// console.log("请求的token为："+token);
	options.header = {
		token: token
	};
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '加载中'
		});
		uni.request({
			url: apiUrl + options.url || '',
			method: options.type || 'GET',
			data: options.data || {},
			header: options.header || {}
		}).then(data => {
			// console.log(data)
			let [err, res] = data;
			uni.hideLoading();
			resolve(res);
		}).catch(error => {
			// console.log(error)
			reject(error)
		})
	});
}
const login = (url, data, options = {}) => {
	options.type = 'GET';
	options.data = data;
	options.url = url;
	return loginRequest(options)
}

const get = (url, data, options = {}) => {
	options.type = 'GET';
	options.data = data;
	options.url = url;
	return request(options)
}

const post = (url, data, options = {}) => {
	options.type = 'POST';
	options.data = data;
	options.url = url;
	return request(options)
}
/**
 * 获取请求返回的res 从中获取sessionid 保存在缓存中
 */
const setSessionCookie = (res) => {
	var cookieStr = "";
	var cookieArr = new Array();
	res.cookies.forEach((item, index, array) => {
		cookieArr.push(item.split(";")[0]);
	});
	cookieStr = cookieArr.join(";");
	wx.setStorageSync('sessionid', cookieStr);
	console.debug("var cookie = " + cookieStr)
	http.setConfig((config) => {
		/* config 为默认全局配置*/
		config.apiUrl = apiUrl; /* 根域名 */
		config.header = {
			AuthTokens: uni.getStorageSync('AuthTokens'), // 演示用
			cookie: uni.getStorageSync("sessionid") // 演示用
		}
		return config
	})
}

export default {
	request,
	get,
	post,
	login,
	setSessionCookie
}